import React, { useEffect, useState } from 'react';
import { Modal, Progress, Button, Space, Typography } from 'antd';
import { message } from 'antd';
import { CheckCircleOutlined, ExclamationCircleOutlined, LoadingOutlined, DownloadOutlined } from '@ant-design/icons';

const { Text } = Typography;

interface ExportProgressModalProps {
    visible: boolean;
    taskId: number | null;
    onClose: () => void;
    onCheckStatus: (taskId: number) => Promise<{ status: string; message: string }>;
    onDownload: (taskId: number) => void;
}

const ExportProgressModal: React.FC<ExportProgressModalProps> = ({
    visible,
    taskId,
    onClose,
    onCheckStatus,
    onDownload
}) => {
    const [status, setStatus] = useState<'running' | 'success' | 'failed'>('running');
    const [progress, setProgress] = useState(0);
    const [statusMessage, setStatusMessage] = useState('准备导出...');
    const [pollTimer, setPollTimer] = useState<NodeJS.Timeout | null>(null);

    // 解析进度信息
    const parseProgress = (progressText: string) => {
        try {
            // 匹配 "正在导出... 进度: 1234/5678 (22%)" 格式
            const progressMatch = progressText.match(/进度:\s*(\d+)\/(\d+)\s*\((\d+)%\)/);
            if (progressMatch) {
                const [, processed, total, percentage] = progressMatch;
                return {
                    processed: parseInt(processed),
                    total: parseInt(total),
                    percentage: parseInt(percentage),
                    message: progressText
                };
            }
            
            // 如果没有匹配到进度格式，检查是否是完成或失败状态
            if (progressText.includes('导出完成')) {
                return { processed: 100, total: 100, percentage: 100, message: progressText };
            }
            
            return { processed: 0, total: 100, percentage: 0, message: progressText };
        } catch (error) {
            return { processed: 0, total: 100, percentage: 0, message: progressText };
        }
    };

    // 轮询检查状态
    const checkStatus = async () => {
        if (!taskId) return;
        
        try {
            const result = await onCheckStatus(taskId);
            const { status: taskStatus, message: taskMessage } = result;
            
            if (taskMessage.includes('导出完成')) {
                setStatus('success');
                setProgress(100);
                setStatusMessage('导出成功完成！');
                if (pollTimer) {
                    clearInterval(pollTimer);
                    setPollTimer(null);
                }
            } else if (taskMessage.includes('导出失败') || taskMessage.includes('失败')) {
                setStatus('failed');
                setStatusMessage(taskMessage);
                if (pollTimer) {
                    clearInterval(pollTimer);
                    setPollTimer(null);
                }
            } else {
                // 解析进度
                const progressInfo = parseProgress(taskMessage);
                setProgress(progressInfo.percentage);
                setStatusMessage(progressInfo.message);
            }
        } catch (error) {
            console.error('检查导出状态失败:', error);
            setStatus('failed');
            setStatusMessage('检查导出状态失败');
            if (pollTimer) {
                clearInterval(pollTimer);
                setPollTimer(null);
            }
        }
    };

    // 开始轮询
    useEffect(() => {
        if (visible && taskId && !pollTimer) {
            // 立即检查一次
            checkStatus();
            
            // 开始轮询
            const timer = setInterval(checkStatus, 2000); // 每2秒检查一次
            setPollTimer(timer);
        }
        
        return () => {
            if (pollTimer) {
                clearInterval(pollTimer);
                setPollTimer(null);
            }
        };
    }, [visible, taskId]);

    // 重置状态
    useEffect(() => {
        if (visible) {
            setStatus('running');
            setProgress(0);
            setStatusMessage('准备导出...');
        }
    }, [visible]);

    // 处理下载
    const handleDownload = () => {
        if (taskId) {
            onDownload(taskId);
            message.success('开始下载文件...');
        }
    };

    // 关闭弹窗
    const handleClose = () => {
        if (pollTimer) {
            clearInterval(pollTimer);
            setPollTimer(null);
        }
        onClose();
    };

    const getStatusIcon = () => {
        switch (status) {
            case 'running':
                return <LoadingOutlined style={{ color: '#1890ff', fontSize: '24px' }} />;
            case 'success':
                return <CheckCircleOutlined style={{ color: '#52c41a', fontSize: '24px' }} />;
            case 'failed':
                return <ExclamationCircleOutlined style={{ color: '#ff4d4f', fontSize: '24px' }} />;
            default:
                return <LoadingOutlined style={{ color: '#1890ff', fontSize: '24px' }} />;
        }
    };

    const getStatusText = () => {
        switch (status) {
            case 'running':
                return '正在导出';
            case 'success':
                return '导出成功';
            case 'failed':
                return '导出失败';
            default:
                return '正在导出';
        }
    };

    const getProgressColor = () => {
        switch (status) {
            case 'success':
                return '#52c41a';
            case 'failed':
                return '#ff4d4f';
            default:
                return '#1890ff';
        }
    };

    return (
        <Modal
            title={
                <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
                    {getStatusIcon()}
                    <span style={{ fontSize: '16px', fontWeight: '600' }}>
                        方法数据导出
                    </span>
                </div>
            }
            open={visible}
            onCancel={handleClose}
            footer={
                <div style={{ textAlign: 'center' }}>
                    {status === 'success' ? (
                        <Space>
                            <Button 
                                type="primary" 
                                icon={<DownloadOutlined />}
                                onClick={handleDownload}
                                size="large"
                            >
                                下载文件
                            </Button>
                            <Button onClick={handleClose} size="large">
                                关闭
                            </Button>
                        </Space>
                    ) : status === 'failed' ? (
                        <Button onClick={handleClose} size="large">
                            关闭
                        </Button>
                    ) : (
                        <Button onClick={handleClose} size="large">
                            后台运行
                        </Button>
                    )}
                </div>
            }
            width={480}
            centered
            closable={status !== 'running'}
            maskClosable={false}
        >
            <div style={{ padding: '24px 0', textAlign: 'center' }}>
                {/* 状态标题 */}
                <div style={{ marginBottom: '24px' }}>
                    <Text strong style={{ fontSize: '18px', color: getProgressColor() }}>
                        {getStatusText()}
                    </Text>
                </div>

                {/* 进度条 */}
                <div style={{ marginBottom: '24px' }}>
                    <Progress
                        percent={progress}
                        status={status === 'failed' ? 'exception' : status === 'success' ? 'success' : 'active'}
                        strokeColor={getProgressColor()}
                        strokeWidth={8}
                        showInfo={true}
                        format={(percent) => `${percent}%`}
                    />
                </div>

                {/* 状态信息 */}
                <div style={{ 
                    background: '#f8f9fa', 
                    padding: '16px', 
                    borderRadius: '8px',
                    border: '1px solid #e9ecef',
                    marginBottom: '16px'
                }}>
                    <Text style={{ 
                        fontSize: '14px', 
                        color: '#666',
                        lineHeight: '1.5'
                    }}>
                        {statusMessage}
                    </Text>
                </div>

                {/* 任务ID信息 */}
                {taskId && (
                    <div style={{ 
                        fontSize: '12px', 
                        color: '#999',
                        textAlign: 'center'
                    }}>
                        任务ID: {taskId}
                    </div>
                )}

                {/* 提示信息 */}
                {status === 'running' && (
                    <div style={{ 
                        marginTop: '16px',
                        padding: '12px',
                        background: '#e6f7ff',
                        border: '1px solid #91d5ff',
                        borderRadius: '6px',
                        fontSize: '13px',
                        color: '#0958d9'
                    }}>
                        💡 数据量较大时导出可能需要几分钟，您可以选择后台运行
                    </div>
                )}

                {status === 'success' && (
                    <div style={{ 
                        marginTop: '16px',
                        padding: '12px',
                        background: '#f6ffed',
                        border: '1px solid #b7eb8f',
                        borderRadius: '6px',
                        fontSize: '13px',
                        color: '#389e0d'
                    }}>
                        ✅ 导出文件已生成，请点击下载按钮获取文件
                    </div>
                )}

                {status === 'failed' && (
                    <div style={{ 
                        marginTop: '16px',
                        padding: '12px',
                        background: '#fff1f0',
                        border: '1px solid #ffccc7',
                        borderRadius: '6px',
                        fontSize: '13px',
                        color: '#cf1322'
                    }}>
                        ❌ 导出过程中发生错误，请稍后重试或联系管理员
                    </div>
                )}
            </div>
        </Modal>
    );
};

export default ExportProgressModal;